package apis

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"common/logger"
	"tylnmall/constant"
	"github.com/jinzhu/gorm"
	"tylnmall/models"
	"time"
	"strings"
	"fmt"
)

func PostListByIdApi(c *gin.Context) {
	type param struct {
		Type   int `json:"type" form:"type"` //请求类别 1.全部帖子,2.根据theme_id查询,3.根据user_id查询,4.根据post_id查询,5.搜索全部精品.6.搜索全部帖子
		Id     int `json:"id" form:"id"`
		UserId int `json:"user_id" form:"user_id"`
		Limit  int `json:"limit" form:"limit"` //每页数量
		Page   int `json:"page" form:"page"`   //页码
	}
	var err error
	var p param
	var Post []*models.Post
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Limit <= 0 {
		p.Limit = 10
	}
	if p.Page <= 0 {
		p.Page = 1
	}
	var count float64
	db := c.MustGet("ty").(*gorm.DB)
	dbExc := db.Limit(p.Limit).Offset((p.Page - 1) * p.Limit).Order("ishead DESC,isbest DESC,createtime DESC")
	switch p.Type {
	case 2:
		if err = dbExc.Where("theme_id = ? and isreviewed = 1", p.Id).Find(&Post).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		if err := db.Where("theme_id = ? and isreviewed = 1", p.Id).Model(&models.Post{}).Count(&count).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		break
	case 3:
		if err = dbExc.Where("user_id = ?", p.Id).Find(&Post).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		if err := db.Where("user_id = ?", p.Id).Model(&models.Post{}).Count(&count).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		break
	case 4:
		if err = dbExc.Where("id = ?", p.Id).Find(&Post).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		if err := db.Where("id = ?", p.Id).Model(&models.Post{}).Count(&count).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		break
	case 5:
		if err = dbExc.Where("isbest = 1 and isreviewed = 1").Find(&Post).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		if err := db.Where("isbest = 1 and isreviewed = 1").Model(&models.Post{}).Count(&count).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		break
	case 6:
		if err = dbExc.Find(&Post).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		if err := db.Model(&models.Post{}).Count(&count).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		break
	default:
		if err = dbExc.Where("isreviewed = 1").Find(&Post).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		if err := db.Where("isreviewed = 1").Model(&models.Post{}).Count(&count).Error; err != nil {
			logger.Error(err)
			c.AbortWithStatus(http.StatusInternalServerError)
			return
		}
		break
	}
	type list struct {
		Post          models.Post `json:"post"`
		UserName      string      `json:"user_name"` //用户信息
		Image         string      `json:"image"`
		IsUserCollect int         `json:"is_user_collect"` //用户是否被收藏
	}
	var List []list
	for _, post := range Post {
		var l list
		l.Post = *post
		var user models.User
		if err = db.Where("id = ?", post.UserId).Find(&user).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		l.UserName = user.Name
		l.Image = user.Image
		if p.Type == 4 {
			var coll []*models.UserCollection
			if err = db.Where("user_id = ? and collection_user_id = ?", p.UserId,user.Id).Find(&coll).Error; err != nil {
				logger.Error(err)
				c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
				return
			}
			if len(coll) > 0 {
				l.IsUserCollect = 1
			}else {
				l.IsUserCollect = 0
			}
		}
		if l.Post.Visit == 0 {
			l.Post.Lastbacktime = ""
		}
		List = append(List, l)
	}
	c.JSON(http.StatusOK, gin.H{"list": &List, "all_num": count})
}

//根据模糊查询查找帖子
func FindPostByNameApi(c *gin.Context) {
	type param struct {
		Val   string `json:"val" form:"val"`
		Limit int    `json:"limit" form:"limit"` //每页数量
		Page  int    `json:"page" form:"page"`   //页码
	}
	var err error
	var p param
	var Post []*models.Post
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Limit <= 0 {
		p.Limit = 10
	}
	if p.Page <= 0 {
		p.Page = 1
	}
	var count float64
	db := c.MustGet("ty").(*gorm.DB)
	dbExc := db.Where("isreviewed = 1")
	if p.Val != "" {
		dbExc = dbExc.Where("title like ? or message like ?", "%"+p.Val+"%", "%"+p.Val+"%")
	}
	if err = dbExc.Limit(p.Limit).Offset((p.Page - 1) * p.Limit).Find(&Post).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	if err := dbExc.Model(&models.Post{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	type list struct {
		Post     models.Post `json:"post"`
		UserName string      `json:"user_name"` //用户信息
		Image    string      `json:"image"`
	}
	var List []list
	for _, post := range Post {
		var l list
		l.Post = *post
		var user models.User
		if err = db.Where("id = ?", post.UserId).Find(&user).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		l.UserName = user.Name
		l.Image = user.Image
		if l.Post.Visit == 0 {
			l.Post.Lastbacktime = ""
		}
		List = append(List, l)
	}
	c.JSON(http.StatusOK, gin.H{"list": &List, "all_num": count})
}

//更新帖子
func UpdatePostVisitApi(c *gin.Context) {
	type param struct {
		Id           int    `json:"id" form:"id"`
		Visit        int    `json:"visit" form:"visit"`
		Createtime   string `json:"createtime" form:"createtime"`     //创建时间
		Lastbacktime string `json:"lastbacktime" form:"Lastbacktime"` //最后回复时间
		Isreviewed   int    `json:"isreviewed" form:"isreviewed"`     //是否审核
	}
	var err error
	var p param
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	var post models.Post
	if err = db.Where("id = ?", p.Id).Find(&post).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	//访问数目+1
	p.Visit = post.Visit
	p.Visit ++
	dates := strings.Split(strings.Split(post.Createtime, "+")[0], "T")
	p.Createtime = dates[0] + " " + dates[1]
	dates = strings.Split(strings.Split(post.Lastbacktime, "+")[0], "T")
	p.Lastbacktime = dates[0] + " " + dates[1]
	p.Isreviewed = 0
	if err = db.Model(&post).Update(&p).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//发布帖子
func PostAddApi(c *gin.Context) {
	type param struct {
		Title        string `json:"title" form:"title"`               //主题名称
		Message      string `json:"message" form:"message"`           //正文
		UserId       int    `json:"user_id" form:"user_id"`           //发帖人id
		ThemeId      int    `json:"theme_id" form:"theme_id"`         //主题id
		Ishead       int    `json:"ishead" form:"ishead"`             //是否置顶   0为置顶,1为不置顶
		Isbest       int    `json:"isbest" form:"isbest"`             //是否加精   0为加精,1为不加精
		Createtime   string `json:"createtime" form:"createtime"`     //创建时间
		Lastbacktime string `json:"lastbacktime" form:"Lastbacktime"` //最后回复时间
		Visit        int    `json:"visit" form:"visit"`               //访问数量
		Back         int    `json:"back" form:"back"`                 //回复数量
	}
	var p param
	var err error
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Title == "" || p.Message == "" || p.UserId == 0 || p.ThemeId == 0 {
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	const base_format = "2006-01-02 15:04:05"
	//获取当前时间
	nt := time.Now()
	var post models.Post
	var timeStr = nt.Format(base_format)
	post.Createtime = timeStr
	post.Lastbacktime = timeStr
	post.Title = p.Title
	post.Message = p.Message
	post.UserId = p.UserId
	post.ThemeId = p.ThemeId
	post.Isreviewed = 0
	db := c.MustGet("ty").(*gorm.DB)
	if err = db.Create(&post).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}

//查看所有未审核帖子
func PostFindByReviewedApi(c *gin.Context) {
	type param struct {
		Limit int `json:"limit" form:"limit"` //每页数量
		Page  int `json:"page" form:"page"`   //页码
	}
	var err error
	var p param
	var Post []*models.Post
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Limit <= 0 {
		p.Limit = 10
	}
	if p.Page <= 0 {
		p.Page = 1
	}
	db := c.MustGet("ty").(*gorm.DB)
	var count float64
	if err = db.Limit(p.Limit).Offset((p.Page - 1) * p.Limit).Where("isreviewed = 0 or isreviewed = 2").Find(&Post).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	if err := db.Where("isreviewed = 0 or isreviewed = 2").Model(&models.Post{}).Count(&count).Error; err != nil {
		logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}
	type list struct {
		Post     models.Post `json:"post"`
		UserName string      `json:"user_name"` //用户信息
		Image    string      `json:"image"`
	}
	var List []list
	for _, post := range Post {
		var l list
		l.Post = *post
		var user models.User
		if err = db.Where("id = ?", post.UserId).Find(&user).Error; err != nil {
			logger.Error(err)
			c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
			return
		}
		l.UserName = user.Name
		l.Image = user.Image
		if l.Post.Visit == 0 {
			l.Post.Lastbacktime = ""
		}
		List = append(List, l)
	}
	c.JSON(http.StatusOK, gin.H{"list": &List, "all_num": count})
}

//审核状态
func PostChangeReviewedApi(c *gin.Context) {
	type param struct {
		Id         int `json:"id" form:"id"`                 //postId
		Isreviewed int `json:"isreviewed" form:"isreviewed"` //状态改变:1.通过,2.不通过
	}
	var err error
	var p param
	if err = c.Bind(&p); err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	if p.Isreviewed > 2 || p.Isreviewed < 1 || p.Id == 0 {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorParamWrong, "err_msg": constant.TranslateErrCode(constant.ErrorParamWrong)})
		return
	}
	db := c.MustGet("ty").(*gorm.DB)
	var Post models.Post
	if err = db.Where("id = ?", p.Id).First(&Post).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	//if len(Post) <= 0{
	//	logger.Error(err)
	//	c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
	//	return
	//}
	fmt.Println(Post.Isreviewed)
	if Post.Isreviewed == p.Isreviewed {
		c.JSON(http.StatusOK, gin.H{"status": "nodone"})
		return
	}
	if err = db.Model(&models.Post{}).Where("id = ?", p.Id).Update("isreviewed", p.Isreviewed).Error; err != nil {
		logger.Error(err)
		c.JSON(http.StatusOK, gin.H{"err_code": constant.ErrorDB, "err_msg": constant.TranslateErrCode(constant.ErrorDB)})
		return
	}
	fmt.Println("-----------------------")
	fmt.Println(Post.Isreviewed)
	c.JSON(http.StatusOK, gin.H{"status": "success"})
}
